package msu.ml;

import msu.ml.util.*;
import msu.ml.core.xml.*;
import msu.ml.core.*;
import java.io.*;
import org.w3c.dom.*;

/**
 * The <a href="../../src/msu/ml/Application.html">Application</a>
 *class represents the main application.
 *
 * @author Reginald M Mead
 * @version 1.0
 *
 * 
 */
public class Application
{
    protected static final String CONF_FILE = ".nexradconf";

   /**
    * Main entry point for program
    * @param args Command line arguments
    */
   public static void main(String [] args) throws Exception
   {
      initApp(); //Create Cache & config file if necessary

      ExperimentXmlParserFactory factory = 
         new ExperimentXmlParserFactory();

      ExperimentXmlParser parser = factory.createParser();
      Experiment experiment = parser.parse(args[0]);
      experiment.execute();
   }

   protected static void initApp()
   {
        loadConf(CONF_FILE);

   }

   protected static void loadConf(String filename)
   {
        File file = new File(filename);
        if(!file.exists())
            createDefaultConf(file);

        ApplicationSettings settings = ApplicationSettings.getInstance();

        Document doc = XmlUtility.parseXmlFile(filename);
        Element element = (Element)(doc.getElementsByTagName("nx_config").item(0));
        if(element != null)
        {
            NodeList list = element.getChildNodes();
            for(int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if(node.getNodeType() == Node.ELEMENT_NODE)
                {
                    settings.setConfig(node.getNodeName(), 
                        node.getTextContent());
                }
            }
        }
   }

   protected static void createDefaultConf(File file)
   {
       try
       {
           PrintWriter fout = new PrintWriter(file);
           fout.println("<?xml version=\"1.0\"?> ");
           fout.println("<nx_config>");
           fout.println("   <verbose>true</verbose>");   
           fout.println("   <benchmark>false</benchmark>");   
           fout.println("   <cache_size>200MB</cache_size>");
           fout.println("</nx_config>");
           fout.close();
       }
       catch(FileNotFoundException e)
       {
           System.out.println("Error - Configuration file could not be created.");
           System.exit(0);
       }
   }
}
